package com.rem.redis.config;

import com.google.common.base.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * redis操作布隆过滤器
 *
 * @author Rem
 * @date 2022/5/24
 */
@Component
public class RedisBloomFilter<T> {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据给定的布隆过滤器添加值
     */
    public void addByBloomFilter(BloomFilterHelper<T> bloomFilterHelper, String key, T value) {
        Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为空");
        int[] offset = bloomFilterHelper.murmurHashOffset(value);
        BitFieldSubCommands commands = BitFieldSubCommands.create();
        for (int i : offset) {
            commands = commands.set(BitFieldSubCommands.BitFieldType.unsigned(1)).valueAt(i).to(1);
        }
        redisTemplate.opsForValue().bitField(key, commands);
    }

    /**
     * 根据给定的布隆过滤器判断值是否存在
     */
    public boolean includeByBloomFilter(BloomFilterHelper<T> bloomFilterHelper, String key, T value) {
        Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为空");
        int[] offset = bloomFilterHelper.murmurHashOffset(value);
        BitFieldSubCommands commands = BitFieldSubCommands.create();
        for (int i : offset) {
            commands = commands.get(BitFieldSubCommands.BitFieldType.unsigned(1))
                    .valueAt(i);
        }
        List<Long> values = redisTemplate.opsForValue().bitField(key, commands);
        assert values != null;
        for (Long val : values) {
            if (val == 0) {
                return false;
            }
        }
        return true;
    }

}

